<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? "编辑房屋" : "新增房屋" }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="house-form"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="小区" prop="complexId">
              <el-select
                v-model="form.complexId"
                placeholder="请选择小区"
                style="width: 100%"
                @change="handleComplexChange"
              >
                <el-option
                  v-for="item in complex"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="楼号" prop="buildingNo">
              <el-input
                v-model="form.buildingNo"
                placeholder="请输入楼号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="单元号" prop="unitNo">
              <el-input
                v-model="form.unitNo"
                placeholder="请输入单元号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="房间号" prop="roomNo">
              <el-input
                v-model="form.roomNo"
                placeholder="请输入房间号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="建筑面积" prop="area">
              <el-input-number
                v-model="form.area"
                :min="1"
                :max="1000"
                :precision="2"
                :step="0.5"
                style="width: 100%"
              >
                <template #append>平方米</template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="房屋状态" prop="status">
              <el-select
                v-model="form.status"
                placeholder="请选择房屋状态"
                style="width: 100%"
              >
                <el-option
                  v-for="item in houseStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="业主" prop="ownerId">
              <el-select
                v-model="form.ownerId"
                placeholder="请选择业主"
                clearable
                filterable
                remote
                :remote-method="handleOwnerSearch"
                :loading="ownerSearchLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in ownerOptions"
                  :key="item.id"
                  :label="`${item.name} (${item.phone})`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
						<el-form-item label="备注" prop="remark">
							<el-input
								v-model="form.remark"
								type="textarea"
								:rows="3"
								placeholder="请输入备注信息"
							/>
						</el-form-item>
					</el-col> -->
        </el-row>

        <!-- 房屋信息卡片预览 -->
        <el-divider>房屋信息预览</el-divider>
        <el-row justify="center">
          <el-col :span="12">
            <el-card shadow="hover" class="preview-card">
              <template #header>
                <div class="preview-header">
                  <span>{{
                    `${form.buildingNo}栋${form.unitNo}单元${form.roomNo}室`
                  }}</span>
                  <el-tag :type="getStatusType(form.status)" v-if="form.status">
                    {{ getStatusLabel(form.status) }}
                  </el-tag>
                </div>
              </template>
              <div class="preview-content">
                <p><label>建筑面积：</label>{{ form.area }} 平方米</p>
                <p>
                  <label>当前业主：</label>
                  <template v-if="currentOwner">
                    {{ currentOwner.name }} ({{ currentOwner.phone }})
                  </template>
                  <span v-else>暂无业主</span>
                </p>
                <p v-if="form.remark">
                  <label>备注信息：</label>{{ form.remark }}
                </p>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-form-item class="form-buttons">
          <el-button type="primary" :loading="loading" @click="submitForm">
            {{ isEdit ? "保存修改" : "立即创建" }}
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getHouse, createHouse, updateHouse } from "@/api/house";
import { getResidents } from "@/api/resident";
import { getComplexList } from "@/api/community";

const route = useRoute();
const router = useRouter();

// 判断是否是编辑模式
const isEdit = computed(() => {
  return route.path.includes("/edit/");
});

// 房屋状态选项
const houseStatusOptions = [
  { value: "Empty", label: "空置" },
  { value: "Occupied", label: "已入住" },
  { value: "Rented", label: "已出租" },
  { value: "Sold", label: "已售出" },
  { value: "Maintained", label: "维修中" },
];

// 表单数据
const formRef = ref(null);
const loading = ref(false);
const form = reactive({
  complexId: undefined,
  buildingNo: "",
  unitNo: "",
  roomNo: "",
  area: 0,
  status: "Empty",
  ownerId: null,
  remark: "",
});

// 业主搜索相关
const ownerSearchLoading = ref(false);
const ownerOptions = ref([]);
const currentOwner = ref(null);

// 表单验证规则
const rules = {
  complexId: [{ required: true, message: "请选择小区", trigger: "change" }],
  buildingNo: [{ required: true, message: "请输入楼号", trigger: "blur" }],
  unitNo: [{ required: true, message: "请输入单元号", trigger: "blur" }],
  roomNo: [{ required: true, message: "请输入房间号", trigger: "blur" }],
  area: [
    { required: true, message: "请输入建筑面积", trigger: "blur" },
    { type: "number", min: 1, message: "面积必须大于0", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择房屋状态", trigger: "change" }],
};

// 搜索业主
const handleOwnerSearch = async (query) => {
  if (query) {
    try {
      ownerSearchLoading.value = true;
      const res = await getResidents({ name: query, pageSize: 10 });
      ownerOptions.value = res.items;
    } catch (error) {
      console.error("搜索业主失败：", error);
    } finally {
      ownerSearchLoading.value = false;
    }
  } else {
    ownerOptions.value = [];
  }
};

// 获取业主信息
const loadOwnerInfo = async (id) => {
  try {
    const res = await getResidents({ id });
    if (res.items.length > 0) {
      currentOwner.value = res.items[0];
    }
  } catch (error) {
    console.error("获取业主信息失败：", error);
  }
};

// 加载房屋信息
const loadHouseInfo = async (id) => {
  try {
    loading.value = true;
    const res = await getHouse(id);
    Object.assign(form, res);
    if (res.ownerId) {
      await loadOwnerInfo(res.ownerId);
    }
  } catch (error) {
    console.error("获取房屋信息失败：", error);
    ElMessage.error("获取房屋信息失败");
  } finally {
    loading.value = false;
  }
};

// 状态标签样式
const getStatusType = (status) => {
  const map = {
    Empty: "info",
    Occupied: "success",
    Rented: "warning",
    Sold: "primary",
    Maintained: "danger",
  };
  return map[status] || "info";
};

const getStatusLabel = (status) => {
  const option = houseStatusOptions.find((item) => item.value === status);
  return option ? option.label : status;
};

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        if (isEdit.value) {
          await updateHouse(route.params.id, form);
          ElMessage.success("修改成功");
        } else {
          await createHouse(form);
          ElMessage.success("创建成功");
        }
        router.push("/house/list");
      } catch (error) {
        console.error("保存失败：", error);
      } finally {
        loading.value = false;
      }
    }
  });
};

// 取消
const cancel = () => {
  router.back();
};

// 监听业主变化
watch(
  () => form.ownerId,
  async (newVal) => {
    if (newVal) {
      await loadOwnerInfo(newVal);
    } else {
      currentOwner.value = null;
    }
  }
);

// 初始化
onMounted(async () => {
  ownerSearchLoading.value = true;
  const res = await getResidents({ pageSize: 100 });
  ownerOptions.value = res.items;
  if (isEdit.value) {
    loadHouseInfo(route.params.id);
  }
});

// 获取小区列表
const complex = ref([]);
const getcomplex = async () => {
  try {
    const data = await getComplexList();
    complex.value = data.items;
  } catch (error) {
    console.error("获取小区列表失败：", error);
  }
};
getcomplex();

// 处理小区变化
const handleComplexChange = (value) => {
  form.complexId = value;
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .house-form {
    max-width: 1200px;
    margin: 0 auto;
    padding-top: 20px;
  }

  .card-header {
    font-size: 18px;
    font-weight: bold;
  }

  .preview-card {
    margin: 20px 0;

    .preview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: bold;
    }

    .preview-content {
      p {
        margin: 10px 0;

        label {
          color: #666;
          margin-right: 10px;
        }
      }
    }
  }

  .form-buttons {
    margin-top: 30px;
    text-align: center;
  }
}
</style>
